package com.db.manage.service;

import com.db.manage.datasource.DynamicDataSource;
import com.db.manage.model.ConnectionConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class QueryService {

    @Autowired
    private ConnectionService connectionService;

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Transactional
    public List<Map<String, Object>> executeQuery(String connectionId, String sql) {
        log.info("开始执行查询: connectionId={}, sql={}", connectionId, sql);
        
        // 获取连接配置
        List<ConnectionConfig> configs = connectionService.getAllConnections();
        log.info("当前所有连接: {}", configs);
        
        // 查找目标连接配置
        ConnectionConfig targetConfig = configs.stream()
            .filter(config -> config.getId().equals(connectionId))
            .findFirst()
            .orElseThrow(() -> new RuntimeException("未找到指定的连接配置: " + connectionId));
            
        // 切换数据源
        log.info("切换数据源到: {}", connectionId);
        dynamicDataSource.setCurrentLookupKey(connectionId);
        dynamicDataSource.afterPropertiesSet();
        
        // 创建新的JdbcTemplate实例，使用动态数据源
        JdbcTemplate targetJdbcTemplate = new JdbcTemplate(dynamicDataSource);
        
        // 验证数据源是否切换成功
        try {
            // 先执行一个简单的查询来验证连接
            targetJdbcTemplate.execute("SELECT 1");
            
            // 获取当前数据库
            String currentDb = targetJdbcTemplate.queryForObject("SELECT DATABASE()", String.class);
            log.info("当前数据库: {}", currentDb);
            
            // 从URL中提取数据库名
            String targetDb = targetConfig.getUrl().split("/")[3].split("\\?")[0];
            log.info("目标数据库: {}", targetDb);
            
            if (!targetDb.equals(currentDb)) {
                // 如果数据库不匹配，尝试切换到正确的数据库
                targetJdbcTemplate.execute("USE " + targetDb);
                currentDb = targetJdbcTemplate.queryForObject("SELECT DATABASE()", String.class);
                log.info("切换后的数据库: {}", currentDb);
                
                if (!targetDb.equals(currentDb)) {
                    throw new RuntimeException("数据源切换失败，当前数据库: " + currentDb + ", 目标数据库: " + targetDb);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("验证数据源失败: " + e.getMessage(), e);
        }
        
        // 执行查询
        log.info("执行SQL查询: {}", sql);
        try {
            List<Map<String, Object>> result = targetJdbcTemplate.queryForList(sql);
            log.info("查询成功，返回 {} 条记录", result.size());
            return result;
        } catch (Exception e) {
            log.error("执行查询失败: connectionId={}, sql={}", connectionId, sql, e);
            throw new RuntimeException("执行查询失败: " + e.getMessage(), e);
        }
    }

    public List<Map<String, Object>> getQueryHistory() {
        // TODO: 实现查询历史功能
        return List.of();
    }

    public void saveQuery(Map<String, String> query) {
        // TODO: 实现查询保存功能
    }
} 